#-*- coding: utf-8 -*-

from django.contrib.auth.models import User
from django.db.models import Q
from utils import detect_identifier_type

class AccountAuthBackend(object):
    """ 自定义用户认证后台
    """

    def authenticate(self, username=None, password=None):

        identifier_type = detect_identifier_type(username)

        if identifier_type == 'email':
            filter = Q(email=username)
        elif identifier_type == 'phone':
            filter = Q(account__phone=username)
        else:
            return None

        try:
            active_user = User.objects.get(filter)
        except User.DoesNotExist:
            return None

        if active_user:
            if active_user.check_password(password):
                return active_user
            else:
                return None
        return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None
